<template>
  <div class="page-container">
    <div class="card-title" v-show="showSearch">
      <el-form size="small" label-width="68px" :model="queryParams" ref="queryForm">
        <el-row :gutter="48">
          <el-col :md="6" :sm="24">
            <el-form-item label="任务编号">
              <el-input v-model="queryParams.id" class="search-item" placeholder="请输入任务编号" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="任务名称">
              <el-input v-model="queryParams.jobName" class="search-item" placeholder="请输入任务名称" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="任务分组">
              <el-input v-model="queryParams.jobGroup" class="search-item" placeholder="请输入任务分组" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="调用目标" v-if="advanced">
              <el-input v-model="queryParams.invokeTarget" class="search-item" placeholder="请输入调用目标" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24" v-if="advanced">
            <el-form-item label="任务状态">
              <el-select v-model="queryParams.status" class="search-item" placeholder="请选择任务状态" clearable>
                <el-option v-for="dict in dict.type.sys_job_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24" v-if="advanced">
            <!-- 创建时间 -->
            <el-form-item label="创建时间" size="small">
              <el-date-picker v-model="queryParams.dataRange" class="search-item" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
          </el-col>
          <!-- 搜索按钮 -->
          <div class="search-content">
            <el-form-item class="search-button">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="handleReset">重置</el-button>
              <el-button type="text" :icon="advanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'" class="advanced-button" @click="toggleAdvanced">
                {{ advanced ? '关闭' : '展开' }}
              </el-button>
            </el-form-item>
          </div>
        </el-row>
      </el-form>
    </div>

    <div class="card">
      <el-row :gutter="10" class="button-container">
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-plus" @click="handleAdd" size="mini" plain>
            新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" icon="el-icon-edit" size="mini" plain :disabled="single" @click="handleUpdate">编辑</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" icon="el-icon-delete" size="mini" plain :disabled="multiple" @click="handleDelete" :loading="buttonLoading">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" icon="el-icon-s-order" size="mini" plain @click="gotoSchedulerJobLog('all')">调度日志</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" :columns="columns" @getTableData="getTableData"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" element-loading-text="正在加载表格数据" :data="tableData" @selection-change="handleSelectionChange" border>
        <template slot="empty">
          <el-empty :image-size="200"></el-empty>
        </template>
        <el-table-column type="selection" width="50" align="center" />
        <!-- 任务名称 -->
        <el-table-column prop="jobName" label="任务名称" align="center" v-if="columns[0].visible" show-overflow-tooltip></el-table-column>
        <!-- 任务分组 -->
        <el-table-column prop="jobGroup" label="任务分组" align="center" v-if="columns[1].visible"></el-table-column>
        <!-- 调用目标 -->
        <el-table-column prop="invokeTarget" label="调用目标" align="center" v-if="columns[2].visible" show-overflow-tooltip></el-table-column>
        <!-- cron执行表达式 -->
        <el-table-column prop="cron" label="cron执行表达式" align="center" v-if="columns[3].visible"></el-table-column>
        <!-- 任务状态 -->
        <el-table-column prop="status" label="任务状态" align="center" v-if="columns[4].visible">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" active-value="true" inactive-value="false" @change="handleJobStatus(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center" v-if="columns[5].visible">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime | dateFilter }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作"  align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" icon="el-icon-edit" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button type="text" size="small" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
            <el-dropdown size="small" style="margin-left: 5px;" @command="(command) => handleCommand(command, scope.row)">
              <el-button size="small" type="text" icon="el-icon-d-arrow-right">更多</el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="runJobOnce" icon="el-icon-caret-right">执行一次</el-dropdown-item>
                <el-dropdown-item command="jobDetail" icon="el-icon-view">任务详细</el-dropdown-item>
                <el-dropdown-item command="schedulerJobLog" icon="el-icon-s-operation">调度日志</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <pagination
        :background="false"
        :total="total"
        :page.sync="queryParams.currentPage"
        :limit.sync="queryParams.pageSize"
        @pagination="getTableData"
      />
    </div>

    <!-- 定时任务信息对话框 -->
    <el-dialog
      :title="schedulerJobTitle"
      width="600px"
      :close-on-click-modal="false"
      :visible="schedulerJobVisible"
      :before-close="handleClose">
      <div class="schedulerJob-wrapper" v-loading="schedulerJobLoading" element-loading-text="正在加载定时任务信息">
        <el-form ref="schedulerJobForm" :model="formData" :rules="rules" label-width="100px" label-position="right">
          <el-row>
            <!-- 任务名称 -->
            <el-col :span="12">
              <el-form-item label="任务名称" prop="jobName">
                <el-input v-model="formData.jobName" placeholder="请输入任务名称" clearable></el-input>
              </el-form-item>
            </el-col>
            <!-- 任务分组 -->
            <el-col :span="12">
              <el-form-item label="任务分组" prop="jobGroup">
                <el-input v-model="formData.jobGroup" placeholder="请输入任务分组" clearable></el-input>
              </el-form-item>
            </el-col>
            <!-- 调用目标 -->
            <el-col :span="24">
              <el-form-item prop="invokeTarget">
                <span slot="label">
                  <el-tooltip placement="top">
                    <div slot="content">
                      Bean调用示例：systemTask.execute('blog')<br/>
                      Class类调用示例：com.zrkizzy.system.task.SystemTask.execute('blog')<br/>
                      参数说明：支持字符串，布尔类型，长整型，浮点型，整型
                    </div>
                    <i class="el-icon-question"></i>
                  </el-tooltip>
                  调用目标
                </span>
                <el-input v-model="formData.invokeTarget" placeholder="请输入调用目标" clearable></el-input>
              </el-form-item>
            </el-col>
            <!-- cron执行表达式 -->
            <el-col :span="24">
              <el-form-item label="cron表达式" prop="cron">
                <el-input v-model="formData.cron" placeholder="请输入cron执行表达式" clearable>
                  <template slot="append">
                    <el-button type="primary" icon="el-icon-time" @click="handleCron">
                      生成表达式
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <!-- 是否并发执行 -->
            <el-col :span="12">
              <el-form-item label="是否并发" prop="concurrent">
                <el-radio-group v-model="formData.concurrent" size="small">
                  <el-radio-button :label="true">允许</el-radio-button>
                  <el-radio-button :label="false">禁止</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <!-- 任务状态 -->
            <el-col :span="12">
              <el-form-item label="任务状态" prop="status">
                <el-radio-group v-model="formData.status" size="small">
                  <el-radio-button v-for="dict in dict.type.sys_job_status" :key="dict.value" :label="dict.value">
                    {{ dict.label }}
                  </el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <!-- 执行策略 -->
            <el-col :span="24">
              <el-form-item label="执行策略" prop="executeStrategy">
                <el-radio-group v-model="formData.executeStrategy" size="small">
                  <el-radio :label="1">立即执行</el-radio>
                  <el-radio :label="2">执行一次</el-radio>
                  <el-radio :label="3">放弃执行</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <!-- 备注 -->
            <el-col :span="24">
              <el-form-item label="任务备注" prop="remark">
                <el-input v-model="formData.remark" placeholder="请输入备注" type="textarea" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer">
        <el-button type="danger" :loading="buttonLoading" @click="handleClose()" size="small" icon="el-icon-error">
          取消
        </el-button>
        <el-button type="success" :loading="buttonLoading" @click="submitForm()" size="small" icon="el-icon-success">
          保存
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="Cron表达式生成器" :visible.sync="openCron" append-to-body destroy-on-close class="scrollbar">
      <div class="cron-wrapper">
        <cron-tab @hide="openCron=false" @fill="confirmCorn" :expression="expression"></cron-tab>
      </div>
    </el-dialog>

    <!-- 详细数据抽屉 -->
    <view-drawer ref="viewDrawer" />
  </div>
</template>
<script>
import ViewDrawer from './components/ViewDrawer'
import Pagination from '../../../components/Pagination/index.vue'
import RightToolbar from '../../../components/RightToolbar/index.vue'
import CronTab from '../../../components/CronTab/index'
import { listSchedulerJob, saveSchedulerJob, getSchedulerJobById, deleteSchedulerJob, changeJobStatus, run } from '../../../api/monitor/scheduler-job'

export default {
  name: 'SchedulerJob',

  dicts: ['sys_job_status'],

  components: { Pagination, RightToolbar, CronTab, ViewDrawer },

  data () {
    return {
      // 高级搜索 展开/关闭
      advanced: false,
      // 是否展示搜索内容
      showSearch: true,
      // 数据总条数
      total: 0,
      // 定时任务对话框是否显示
      schedulerJobVisible: false,
      // 数据表格等待框
      loading: false,
      // 查询参数
      queryParams: {
        // 页数
        currentPage: 1,
        // 页面大小
        pageSize: 10,
        // 任务编号
        id: undefined,
        // 调用目标
        invokeTarget: undefined,
        // 任务名称
        jobName: undefined,
        // 任务分组
        jobGroup: undefined,
        // 任务状态
        status: undefined,
        // 时间范围
        dataRange: []
      },
      // 定时任务表单对象
      formData: {
        // 是否并发执行
        concurrent: undefined,
        // cron执行表达式
        cron: undefined,
        // 执行策略
        executeStrategy: undefined,
        // 调用目标
        invokeTarget: undefined,
        // 任务分组
        jobGroup: undefined,
        // 任务名称
        jobName: undefined,
        // 备注
        remark: undefined,
        // 任务状态
        status: undefined
      },
      // 定时任务表单校验规则
      rules: {
        // 任务名称
        jobName: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
        // 调用目标
        invokeTarget: [{ required: true, message: '请输入调用目标', trigger: 'blur' }],
        // cron表达式
        cron: [{ required: true, message: 'cron表达式不能为空', trigger: 'blur' }]
      },
      // 定时任务对话框等待框
      schedulerJobLoading: false,
      // 对话框按钮等待框
      buttonLoading: false,
      // 列信息
      columns: [
        // 任务名称
        { key: 0, label: '任务名称', visible: true },
        // 任务分组
        { key: 1, label: '任务分组', visible: true },
        // 调用目标
        { key: 2, label: '调用目标', visible: true },
        // cron执行表达式
        { key: 3, label: 'cron执行表达式', visible: true },
        // 任务状态
        { key: 4, label: '任务状态', visible: true },
        { key: 5, label: '创建时间', visible: true }
      ],
      // 表格数据
      tableData: [],
      // 表头选中的数据
      ids: [],
      // 多数据禁用
      single: true,
      // 单数据禁用
      multiple: true,
      // 对话框标题
      schedulerJobTitle: '',
      // 是否显示Cron表达式弹出层
      openCron: false,
      // cron表达式值
      expression: ''
    }
  },

  mounted () {
    // 查询表格数据
    this.getTableData()
  },

  methods: {
    // 获取表格数据
    getTableData () {
      // 开启加载框
      this.loading = true
      listSchedulerJob(this.queryParams).then((res) => {
        // 赋值数据参数
        this.tableData = res.list
        this.total = res.total
        // 关闭等待框
        this.loading = false
      }).catch(() => {
        // 确保加载框可以关闭
        this.loading = false
      })
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    // 点击查询按钮
    handleQuery () {
      this.queryParams.currentPage = 1
      this.getTableData()
    },
    // 点击重置按钮
    handleReset () {
      // 任务编号
      this.queryParams.id = undefined
      // 调用目标
      this.queryParams.invokeTarget = undefined
      // 任务名称
      this.queryParams.jobName = undefined
      // 任务状态
      this.queryParams.status = undefined
      // 任务分组
      this.queryParams.jobGroup = undefined
      this.queryParams.dataRange = []
    },
    // 打开定时任务信息对话框
    handleOpen () {
      // 清除表单数据
      this.reset()
      this.schedulerJobVisible = true
    },
    // 关闭定时任务对话框表单
    handleClose () {
      this.reset()
      this.schedulerJobVisible = false
    },
    // 点击新增按钮
    handleAdd () {
      this.schedulerJobTitle = '新增定时任务'
      this.handleOpen()
    },
    // 点击编辑按钮
    handleUpdate (row) {
      // 修改对话框标题
      this.schedulerJobTitle = '更新定时任务'
      // 获取到传来的ID
      const schedulerJobId = row.id || this.ids
      // 打开加载框
      this.schedulerJobLoading = true
      // 根据定时任务ID获取对应的数据
      getSchedulerJobById(schedulerJobId).then((res) => {
        // 赋值当前的定时任务数据
        this.formData = res
        // 打开编辑定时任务对话框
        this.schedulerJobVisible = true
        // 关闭加载框
        this.schedulerJobLoading = false
      }).catch(() => {
        // 关闭加载框
        this.schedulerJobLoading = false
      })
    },
    // 点击删除事件
    handleDelete (row) {
      const that = this
      let schedulerJobIds = []
      if (row.id) {
        schedulerJobIds.push(row.id)
      } else {
        schedulerJobIds = this.ids
      }
      this.$confirm('是否确认删除选中的定时任务数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        that.buttonLoading = true
        that.loading = true
        deleteSchedulerJob(schedulerJobIds).then((res) => {
          that.buttonLoading = false
          that.$message.success('删除成功')
          // 刷新数据
          that.getTableData()
        }).catch(() => {
          // 确保加载框会关闭
          that.buttonLoading = false
          that.loading = false
        })
      }).catch(() => {})
    },
    // 提交表单
    submitForm () {
      const that = this
      this.$refs.schedulerJobForm.validate(valid => {
        // 校验未通过则直接返回
        if (!valid) return
        // 开启加载框
        that.buttonLoading = true
        that.schedulerJobLoading = true
        // 提交表单
        saveSchedulerJob(that.formData).then((res) => {
          // 根据是否存在ID输出对应消息
          if (that.formData.id) {
            // 输出更新成功信息
            that.$message.success('定时任务信息更新成功')
          } else {
            // 输出添加成功消息
            that.$message.success('定时任务添加成功')
          }
          // 刷新表单数据并关闭对话框
          that.handleClose()
          // 刷新定时任务数据
          that.getTableData()
          // 关闭加载框
          that.buttonLoading = false
          that.schedulerJobLoading = false
        }).catch(() => {
          // 关闭加载框
          that.buttonLoading = false
          that.schedulerJobLoading = false
        })
      })
    },
    // 重置表单
    reset () {
      // 清除校验条件
      this.formData = {
        // 定时任务ID
        id: undefined,
        // 调用目标
        invokeTarget: undefined,
        // 任务名称
        jobName: undefined
      }
      // 清除表单校验
      this.resetForm('schedulerJobForm')
    },
    // 多选框
    handleSelectionChange (selection) {
      // 获取当前选中数组的ID
      this.ids = selection.map(item => item.id)
      // 表头的编辑是否可以点击
      this.single = selection.length !== 1
      // 表头的删除是否可以点击
      this.multiple = !selection.length
    },
    // Corn表达式操作
    handleCron () {
      this.expression = this.formData.cron
      this.openCron = true
    },
    // 确定表达式返回值
    confirmCorn (value) {
      this.formData.cron = value
    },
    // 更多按钮选择内容
    handleCommand (command, row) {
      switch (command) {
        case 'jobDetail':
          this.$refs.viewDrawer.handleView(row)
          break
        case 'runJobOnce':
          this.handleJobRun(row.id)
          break
        case 'schedulerJobLog':
          this.gotoSchedulerJobLog(row.id)
          break
        default: break
      }
    },
    // 更新任务状态
    handleJobStatus (row) {
      const data = {
        id: row.id,
        jobGroup: row.jobGroup,
        status: row.status
      }
      changeJobStatus(data).then(() => {
        this.$message.success('定时任务状态更新成功')
      }).catch(() => {})
    },
    // 执行一次定时任务
    handleJobRun (id) {
      run(id).then((res) => {
        if (res) {
          this.$message.success('任务执行成功')
        }
      }).catch(() => {})
    },
    // 跳转到调度日志
    gotoSchedulerJobLog (id) {
      this.$router.push('/system-content/scheduler-job-log/' + id)
    }
  }
}

</script>

<style lang="scss" scoped>
.schedulerJob-wrapper {
  padding: 20px 30px;
}
.cron-wrapper {
  padding: 10px 30px;
}
</style>
